from django.db.models import Q
from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from course.courseser import CategorySerializer, Category, CourseSerializer, CourseIndexSerializer
from course.models import CategoryModel, CourseModel
from utils.myredis import redis_toll


# Create your views here.

class CategoryView(APIView):
    def get(self, request):
        all_cate = CategoryModel.objects.filter(parent=None, is_home=True, is_show=True).order_by('order')
        ser = CategorySerializer(instance=all_cate, many=True)
        for i in ser.data:
            i['children'] = i['children'][:3]
        return Response(ser.data)


class NowCate(APIView):
    def get(self, request):
        id = request.query_params.get('id')
        info = CategoryModel.objects.filter(id=id, parent=None, is_home=True, is_show=True).first()
        ser = CategorySerializer(info)
        two_cate = CategoryModel.objects.filter(parent=id, is_show=True).values_list('id', flat=True)
        course = CourseModel.objects.filter(category__in=two_cate, is_show=True, is_home=True).order_by(
            'order').values()[:4]
        course_info = ser.data
        course_info['course'] = course
        return Response({'message': 'ok', 'data': course_info, 'code': 200})


class Direction(APIView):
    def get(self, request):
        all_cate = CategoryModel.objects.filter(parent=None, is_show=True).order_by('order')
        ser = Category(all_cate, many=True)
        return Response({'code': 200, 'message': 'ok', 'data': ser.data})


class ChildCate(APIView):
    def get(self, request):
        pid = int(request.query_params.get('pid'))
        if pid == 0:
            child = CategoryModel.objects.exclude(parent=None, is_show=False).order_by('order')
        else:
            child = CategoryModel.objects.filter(parent=pid, is_show=True).order_by('order')
        ser = Category(child, many=True)
        return Response({'code': 200, 'message': 'ok', 'data': ser.data})


class Pagination(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'size'
    page_query_param = 'page'


class CourseList(ListAPIView):
    queryset = CourseModel.objects.all()
    serializer_class = CourseSerializer
    pagination_class = Pagination

    def get_queryset(self):
        direction = int(self.request.query_params.get('direction'))
        cate = int(self.request.query_params.get('cate'))
        level = int(self.request.query_params.get('level'))
        order = self.request.query_params.get('order')
        query = Q()
        if cate != 0:
            query &= Q(category=cate)
        if direction > 0 and cate == 0:
            all_cate = CategoryModel.objects.filter(parent=direction).values()
            child = []
            for i in all_cate:
                child.append(i['id'])
            query &= Q(category__in=child)
        if level > 0:
            query &= Q(level=level)
        if order:
            return self.queryset.filter(query).order_by(order)
        else:
            return self.queryset.filter(query)


class Detail(APIView):
    def get(self, request):
        id = request.query_params.get('id')
        info = CourseModel.objects.filter(id=id).first()
        info.read += 1
        info.save()
        ser = CourseSerializer(info)
        return Response({'code': 200, 'message': 'ok', 'data': ser.data})


class HotWordView(HaystackViewSet):
    index_models = [CourseModel]
    serializer_class = CourseIndexSerializer
    pagination_class = Pagination

    def list(self, request, *args, **kwargs):
        text = request.query_params.get('text', '')
        if text:
            redis_toll.hot_add("hot_word", text)
        data = super().list(request, *args, **kwargs).data
        for i in data['results']:
            i['cover'] = "http://127.0.0.1:8000/uploads" + i['cover']
        return Response(data)


class GetHotWord(APIView):
    def get(self, request):
        data = redis_toll.hot_get("hot_word", 4)
        return Response(data)
